package com.bbs.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bbs.entity.Article;
import com.bbs.service.SearchService;
import com.bbs.util.ChangeUtil;
import com.bbs.util.Page;
import com.bbs.util.Render;

public class SearchServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("_method");
		if(method == null || "".equals(method)) {
			index(request, response);
		} else {
			response.sendError(404);
		}
	}
	
	private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String scontent = request.getParameter("s_content");
		String pid = request.getParameter("page");
		int p = new ChangeUtil().changeStringToInt(pid);
		HttpSession session = request.getSession();
		if(p == 1) {
			
			session.setAttribute("scontent", scontent);
		}
		if(p >=2) {
			scontent = (String)session.getAttribute("scontent");
		}
		Page page = new Page();
		SearchService searchService = new SearchService();
		page.setPageSize(20);
		page.setTotleSize(searchService.searchCount(scontent));
		page.setCurrentPage(p);
		
		if(p <= 0) {
			response.sendError(404);
		} else {
			List<Article> searchList = searchService.findList(scontent, page);
			request.setAttribute("searchList", searchList);
			request.setAttribute("page", page);
			Render.rend("search", request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
